package com.yaolaizaixian.merchant;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.LoginModel;
import com.yaolaizaixian.merchant.home.WebActivity;
import com.yaolaizaixian.merchant.net.DES3Util;
import com.yaolaizaixian.merchant.net.MD5Util;
import com.yaolaizaixian.merchant.net.SignUtils;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.MyUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity {

    private static final String TAG = "LoginActivity";
    @BindView(R.id.et_login_name)
    EditText etLoginName;
    @BindView(R.id.ll_login_user)
    AutoRelativeLayout llLoginUser;
    @BindView(R.id.et_login_pass)
    EditText etLoginPass;
    @BindView(R.id.ll_login_pwd)
    AutoRelativeLayout llLoginPwd;
    @BindView(R.id.rl_login)
    AutoRelativeLayout rlLogin;
    @BindView(R.id.tv_help)
    TextView tvHelp;
    @BindView(R.id.ll_help)
    AutoLinearLayout llHelp;
    @BindView(R.id.ll_all)
    AutoRelativeLayout llAll;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.tv_user)
    TextView tvUser;
    @BindView(R.id.tv_pass)
    TextView tvPass;
    @BindView(R.id.rl_splash)
    RelativeLayout rlSplash;
    private String user;
    private String pass;
    private Dialog progressDialog;
    private boolean isanim = true;
    private long sleepTime = 2000;
    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;

                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);

                    if (baseModel.isFlag()) {

                        final LoginModel loginModel = GsonUtil.jsonToBean(result, LoginModel.class);
                        rlLogin.setClickable(true);
                        //保存店鋪名称
                        SharedPreferencesUtil.saveString(getApplicationContext(), "Shopname", loginModel.getData().getStore().getStorename());
                        //用户名称
                        SharedPreferencesUtil.saveString(getApplicationContext(), "username", loginModel.getData().getEmployee().getName());
                        //员工部门
                        SharedPreferencesUtil.saveString(getApplicationContext(), "menname", loginModel.getData().getEmployee().getDepartmentname());
                        //店铺id
                        SharedPreferencesUtil.saveString(getApplicationContext(), "shopsysno", loginModel.getData().getEmployee().getShopsysno());
                        //员工id
                        SharedPreferencesUtil.saveString(getApplicationContext(), "usersysno", loginModel.getData().getEmployee().getSysno());
                        //商户id
                        SharedPreferencesUtil.saveString(getApplicationContext(), "vendorsysno", loginModel.getData().getEmployee().getVendorsysno());
                        //店铺地址
                        SharedPreferencesUtil.saveString(getApplicationContext(), "shopAddress", loginModel.getData().getStore().getAddress());
                        //店铺image
                        SharedPreferencesUtil.saveString(getApplicationContext(), "shopImage", loginModel.getData().getStore().getStorelogoimage());
                        //商家名称
                        SharedPreferencesUtil.saveString(getApplicationContext(), "shopvendor", loginModel.getData().getVendor().getVendorname());
                        //登录签名 登录踢出
                        SharedPreferencesUtil.saveString(getApplicationContext(), "loginSign", loginModel.getData().getLoginSign());

                        startActivity(new Intent(LoginActivity.this, HomeActivity.class));

                        progressDialog.dismiss();

                        finish();

                    } else {

                        progressDialog.dismiss();
                        rlLogin.setClickable(true);
                        Toast.makeText(LoginActivity.this, baseModel.getErrorMsg(), Toast.LENGTH_SHORT).show();

                    }

                    break;

            }
        }
    };

    @Override
    public void initView() {

        setContentView(R.layout.activity_login);

    }

    @Override
    public void initData() {

        //员工id
        final String usersysno = SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", "");
        new Thread(new Runnable() {
            @Override
            public void run() {

                //员工id
                if (!TextUtils.isEmpty(usersysno)) {

                    // 自动登录，在登录之前
                    long start = System.currentTimeMillis();
                    long costTime = System.currentTimeMillis() - start;
                    //wait
                    if (sleepTime - costTime > 0) {
                        try {

                            Thread.sleep(sleepTime - costTime);

                        } catch (InterruptedException e) {

                            e.printStackTrace();
                        }
                    }
                    //enter main screen
                    startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                    finish();
                } else {

                    rlSplash.setVisibility(View.GONE);
                    weiyi(ivLogo);
                    jianbian(llLoginUser, 2000);
                    jianbian(llLoginPwd, 2300);
                    jianbian(rlLogin, 2600);
                    jianbian(llHelp, 2900);

                }
            }
        }).start();


        //点击隐藏键盘
        llAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                MyUtils.hind(LoginActivity.this);
            }
        });
        //帮助说明 加入横线
        tvHelp.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

//        etLoginName
        etLoginName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                    // 此处为得到焦点时的处理内容
                    // llLoginUser.setBackground(getResources().getDrawable(R.drawable.bg_edittext_focused));

                    //tvweiyi(tvUser);
                    if (TextUtils.isEmpty(etLoginName.getText().toString().trim()) && isanim == true) {

                        startAnimator(tvUser);
                        isanim = false;

                    }

                } else {

                    // 此处为失去焦点时的处理内容
                    // llLoginUser.setBackground(getResources().getDrawable(R.drawable.eidttextshape));
                    if (TextUtils.isEmpty(etLoginName.getText().toString().trim())) {

                        tvUser.clearAnimation();
                        isanim = true;

                    }
                }
            }
        });

        etLoginPass.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    // llLoginPwd.setBackground(getResources().getDrawable(R.drawable.bg_edittext_focused));

                    if (TextUtils.isEmpty(etLoginPass.getText().toString().trim())) {
                        startAnimator(tvPass);
                    }

                } else {
                    // 此处为失去焦点时的处理内容
                    //llLoginPwd.setBackground(getResources().getDrawable(R.drawable.eidttextshape));

                    /*if (TextUtils.isEmpty(etLoginPass.getText().toString().trim()))
                    {
                        endAnimator(tvPass);
                    }*/

                    if (TextUtils.isEmpty(etLoginPass.getText().toString().trim())) {
                        tvPass.clearAnimation();
                        isanim = true;
                    }
                }
            }
        });

    }

    //展示正在加载
    private void showdia() {

        progressDialog = new Dialog(LoginActivity.this, R.style.progress_dialog);
        progressDialog.setContentView(R.layout.dialog);
        progressDialog.setCancelable(true);
        progressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        TextView msg = (TextView) progressDialog.findViewById(R.id.id_tv_loadingmsg);
        msg.setText("正在登录中。。");
        progressDialog.show();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setSwipeBackEnable(false);

    }

    private void login(String username, String password) {

        try {

            HashMap<String, String> sortedParams = new HashMap<String, String>();
            // sysNo 值  3des加密
            sortedParams.put("accountID", username);
            sortedParams.put("pwd", MD5Util.md5(password));
            sortedParams.put("access_token", BaseInfo.ACCESS_TOKEN);//固定传参
            String sign = SignUtils.sign(BaseInfo.SERVICEKEY, sortedParams);
            final String url = BaseInfo.URL + "login/login.do";
            Log.e(TAG, url);
            Map<String, String> params = new HashMap<String, String>();
            params.put("appid", "600000");
            params.put("sign_type", "APP");
            params.put("sign", sign);

            for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
                params.put(entry.getKey(), URLEncoder.encode(DES3Util.encode(entry.getValue(), BaseInfo.SERVICEKEY)));
            }

            OkHttpUtils
                    .post()
                    .url(url)
                    .params(params)
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {

            e.printStackTrace();

            progressDialog.dismiss();

        }

    }

    @OnClick({R.id.rl_login, R.id.ll_help})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_login:

                user = etLoginName.getText().toString().trim();
                pass = etLoginPass.getText().toString().trim();

                if (TextUtils.isEmpty(user)) {

                    Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                    return;

                } else if (TextUtils.isEmpty(pass)) {

                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();

                    return;

                }
                else if(!MyUtils.isMobile(user))
                {
                    Toast.makeText(this, "手机号格式错误", Toast.LENGTH_SHORT).show();

                    return;
                }
                else {

                    showdia();
                    login(etLoginName.getText().toString().trim(),
                            etLoginPass.getText().toString().trim());
                }

                break;

            case R.id.ll_help:

                Intent intent = new Intent(LoginActivity.this, WebActivity.class);
                startActivity(intent);

                break;
        }
    }


    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

            progressDialog.dismiss();
            rlLogin.setClickable(true);
            Toasty.error(LoginActivity.this, "网络异常", Toast.LENGTH_SHORT, true).show();
            return;

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);

        }

    }

    public void jianbian(View view, long time) {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);//初始化操作，参数传入0和1，即由透明度0变化到透明度为1
        view.startAnimation(alphaAnimation);//开始动画
        alphaAnimation.setFillAfter(true);//动画结束后保持状态
        alphaAnimation.setDuration(800);//动画持续时间，单位为毫秒
        //设置动画延时时间
        alphaAnimation.setStartOffset(time);
        alphaAnimation.start();
    }


    public void weiyi(View view) {
        //位移动画
        Animation animation = new TranslateAnimation(0, 0, 300, 0);
        animation.setDuration(800);
        animation.setRepeatCount(0);//动画的重复次数
        animation.setFillAfter(true);//设置为true，动画转化结束后被应用
        animation.setStartOffset(1000);
        view.startAnimation(animation);//开始动画
    }


    public void tvweiyi(View view) {
        //位移动画
        Animation animation = new TranslateAnimation(0, 0, 0, -50);
        animation.setDuration(800);
        animation.setRepeatCount(0);//动画的重复次数
        animation.setFillAfter(true);//设置为true，动画转化结束后被应用
        view.startAnimation(animation);//开始动画
    }


    /*新建类，类名startAnimator要与layout中android:onClick="startAnimator"的名称相同*/
    public void startAnimator(View view) {
        // ObjectAnimator.ofFloat(mImageView,"scaleX",0.0f,1f).setDuration(3000).start();//这是没有写animator时直接在这里写动画效果。上面已经写了animator，所以代码如下：
   /*     AnimationSet animator =(AnimationSet) loadAnimator(this, R.anim.loginanim);
        //animator.setTarget(view);
        animator.start();*/
        AnimationSet animationSet = (AnimationSet) AnimationUtils.loadAnimation(LoginActivity.this, R.anim.loginanim);
        animationSet.setFillAfter(true);
        view.startAnimation(animationSet);

    }

    /*新建类，类名startAnimator要与layout中android:onClick="startAnimator"的名称相同*/
    public void endAnimator(View view) {
        // ObjectAnimator.ofFloat(mImageView,"scaleX",0.0f,1f).setDuration(3000).start();//这是没有写animator时直接在这里写动画效果。上面已经写了animator，所以代码如下：
   /*     AnimationSet animator =(AnimationSet) loadAnimator(this, R.anim.loginanim);
        //animator.setTarget(view);
        animator.start();*/
        AnimationSet animationSet = (AnimationSet) AnimationUtils.loadAnimation(LoginActivity.this, R.anim.loginanim);
        animationSet.setFillAfter(true);
        view.startAnimation(animationSet);

    }


}
